var grid;
var form;
var form1;
$(function () {

    $(".select2").select2();

    var flag = false;
    //分配权限
    if (localStorage.getItem("roleId") == 4) {
        //超级管理员
    } else if (localStorage.getItem("roleId") == 1) {
        //管理员
    } else {
        //教师、学生具有的权限基本相同、包括通知的查看、基本信息的查看、编辑、修改密码
        flag = true;
        $("#addNewBtnMessage").css("display", "none");
        // $("#search").css("display", "none");
    }

    var pageNo = 1;
    var pageSize = 10;
    var grid_selector = "#grid-table";
    var pager_selector = "#grid-pager";
    //初始化数据表格
    grid = $(grid_selector).jqGrid({
        datatype: "json",
        url: '../userList/selectAllUserList',
        mtype: 'GET',
        page: pageNo,
        postData: {
            "stunumber": $("#stunumber1").val(),
            "phone": $("#phone1").val(),
            "classs": $("#classs1").val(),
            "realname": $("#realname1").val(),
            "userId": localStorage.getItem("userId")
        },
        height: 380,
        width: 300,
        colNames: ['学院', "班级", "学号", "住址", "真实姓名", "手机号", "权限名称", "注册时间", "备注", "审核状态", "操作"],
        colModel: [
            {name: 'academy', index: 'academy', sortable: false, align: 'center', width: 200},
            {name: 'classs', index: 'classs', sortable: false, align: 'center', width: 200},
            {name: 'stunumber', index: 'stunumber', sortable: false, align: 'center', width: 200},
            {name: 'address', index: 'address', sortable: false, align: 'center', width: 200},
            {name: 'realname', index: 'realname', sortable: false, align: 'center', width: 200},
            {name: 'phone', index: 'phone', sortable: false, align: 'center', width: 200},
            {name: 'rolename', index: 'rolename', sortable: false, align: 'center', width: 200},
            {name: 'timeStr', index: 'timeStr', sortable: false, align: 'center', width: 250},
            {name: 'remark', index: 'remark', sortable: false, align: 'center', width: 200},
            {
                name: 'issh', index: 'issh', fixed: true, sortable: false, resize: false, width: 100,
                formatter: function (cellvalue, options, rowObject) {
                    if (cellvalue == 0)
                        if (flag != true)
                            return "<button class='btn btn-default btn-xs' onclick='check(\"" + rowObject.id + "\")'>未审核</button>";
                        else
                            return "<button class='btn btn-default btn-xs'>未审核</button>";
                    else
                        return "<button class='btn btn-success btn-xs'>已审核</button>";
                }
            },
            {
                name: 'id', index: 'id', fixed: true, sortable: false, resize: false, width: 200,
                formatter: function (cellvalue, options, rowObject) {
                    if (flag != true)
                        return "<button class='btn btn-vimeo btn-xs' onclick='resetPassword(\"" + rowObject.id + "\")'><i class='fa fa-edit button-in-i'></i>重置密码</button>"
                            + "<button  class='btn btn-twitter btn-xs' onclick='openEdit(\"" + rowObject.id + "\")'><i class='fa fa-edit button-in-i'></i>编辑</button>"
                            + "<button class='btn btn-danger btn-xs' onclick='openDelete(\"" + rowObject.id + "\")' ><i class='fa fa-trash button-in-i'></i>删除</button>";
                    else
                        return "<button class='btn btn-vimeo btn-xs' onclick='EidtPassWord(\"" + rowObject.id + "\")'><i class='fa fa-edit button-in-i'></i>修改密码</button>"
                            + "<button  class='btn btn-twitter btn-xs' onclick='openEdit(\"" + rowObject.id + "\")'><i class='fa fa-edit button-in-i'></i>编辑</button>";

                }
            },
        ],
        viewrecords: true,
        rowNum: pageSize,
        rownumbers: true,//添加左侧行号
        rowList: [10, 15, 20],
        pager: pager_selector,
        altRows: true,
        multiselect: false,
        loadComplete: function (data) {
            var table = this;
            setTimeout(function () {
                updatePagerIcons(table);
            }, 0);
            var h = $(window).height() - ($('#grid-pager')[0].offsetHeight + 15) - ($('.result-table .box')[0].offsetTop + $('.content .col-xs-12')[0].offsetTop + $('.ui-jqgrid-bdiv')[0].offsetTop + 3);
            $('.ui-jqgrid-bdiv').height(h);
            /*var h = $(window).height() - ($('#grid-pager')[0].offsetHeight + 15) - ($('.result-table .box')[0].offsetTop + $('.ui-jqgrid-bdiv')[0].offsetTop + 3);
            $('.ui-jqgrid-bdiv').height(h);*/
        },
        autowidth: true,
        jsonReader: jsonReader,   // json中代表实际模型数据的入口
        rownumWidth: 55,
        prmNames: prmNames,
        recordtext: "显示 {0} - {1} 条 , 共 {2} 条",
        emptyrecords: "没有记录",
        loadtext: "正在加载...",
        pgtext: "第 {0} 页  ,共 {1} 页"
    });
    //初始化分页条
    showNavGrid(grid_selector, pager_selector);
    //初始化信息校验表单
    form = $("#addform").validate({
        errorElement: 'div',
        errorClass: 'help-block messages',
        focusInvalid: false,
        highlight: validateHighlight,
        success: validateSuccess,
        errorPlacement: errorPlacement
    });
    form1 = $("#Editform").validate({
        errorElement: 'div',
        errorClass: 'help-block messages',
        focusInvalid: false,
        highlight: validateHighlight,
        success: validateSuccess,
        errorPlacement: errorPlacement
    });

    //添加新公告
    $("#addNewBtn").click(function () {
        addNewBtn();
    });
    //编辑
    $("#openEdit").click(function () {
        openEdit(str);
    });
    //查询
    $("#queryBtn").click(function () {
        var filters = {
            "stunumber": $("#stunumber1").val(),
            "phone": $("#phone1").val(),
            "classs": $("#classs1").val(),
            "realname": $("#realname1").val(),
            "userId": localStorage.getItem("userId")
        }
        grid.jqGrid("setGridParam", {postData: filters, page: 1});
        grid.trigger('reloadGrid');
    });
    //清空
    $("#clearBtn").click(function () {
        $("#stunumber1").val("");
        $("#phone1").val("");
        $("#classs1").val("");
        $("#realname1").val("");
    });
    //保存
    $("#saveBtn").click(function () {
        doSubmit();
    });

    /*
     * 修改密码
     */
    //账号信息校验表单
    var indexForm = $("#editPasswordForm").validate({
        rules: {
            indexPass: {
                required: true
            }
            , indexPass1: {
                required: true
                , rangelength: [5, 16]
            }
            , indexPass2: {
                required: true
                , equalTo: "#indexPass1"
            }
        },
        messages: {
            indexPass: {
                required: "原始密码不能为空"
            }
            , indexPass1: {
                required: "新密码不能为空"
                , rangelength: "密码长度在5-16位之间"
            }
            , indexPass2: {
                required: "确认密码不能为空"
                , equalTo: "两次输入的密码不一致"
            }
        },
        submitHandler: function (form) {
            indexDoSubmit();
        },
        errorElement: 'div',
        errorClass: 'help-block messages',
        focusInvalid: false,
        highlight: validateHighlight,
        success: validateSuccess,
        errorPlacement: errorPlacement
    });

    $("#indexUpdateBtn").click(function () {
        if (indexForm.form()) {
            indexDoSubmit();
        }
    });
});

//审核用户
function check(id) {
    bootbox.confirm("确定要审核通过该用户吗？", function (result) {
        if (result) {
            $.post("../userList/checkUser", {
                "id": id,
                "_method": "PUT",
            }, function (data) {
                if (data.resultCode = 200) {
                    bootbox.alert("审核成功！");
                } else {
                    bootbox.alert("审核失败！");
                }
                grid.trigger('reloadGrid');
            });
        }
    });
}

//修改密码
function indexDoSubmit() {
    $.post("../userList/changePassword", {
        id: $("#userid").val(),
        oldPassword: $("#indexPass").val(),
        password: $("#indexPass1").val(),
        "_method": "PUT",
    }, function (data) {
        if (data.resultCode != 200) {
            bootbox.alert(data.resultMessage);
        } else {
            bootbox.alert(data.resultMessage);
            $('#indexEditP').modal('hide');
        }
    });
}

function EidtPassWord(id) {
    $("#editPassword").html("修改密码");
    $("#indexPass").val("");
    $("#indexPass1").val("");
    $("#indexPass2").val("");
    $("#indexEditP").modal();
    $("#userid").val(id);
    $("#idLablePass").css("display", "none");
}

//添加新用户
function addNewBtn() {
    loadPage("../userList/skipToUserAdd")
}

//跳转到回收站
function toTrash() {
    loadPage("../goodsInfo/skipToUserList");
}
//重置密码
function resetPassword(id) {
    bootbox.confirm("确定要重置该管理员的密码吗？重置后密码为【000000】！", function (result) {
        if (result) {
            $.post("../userList/resetPassWord", {
                "id": id,
                "_method": "PUT",
            }, function (data) {
                if (data.resultCode = 200) {
                    bootbox.alert("密码重置成功！");
                } else {
                    bootbox.alert("密码重置失败！");
                }
                grid.trigger('reloadGrid');
            });
        }
    });
}

//打开编辑表单
function openEdit(id) {
    clearForm();
    $("#editmyModal").modal();
    $("#modeltitle1").html("用户编辑页面");
    $("#idLable1").css("display", "none");
    //Ajax请求查询编辑的信息
    $.post("../userList/selectAllUserListByPrimaryKey", {
        "id": id,
        "_method": "GET",
    }, function (data) {
        $("#id").val(data[0].id);
        $("#stunumber").val(data[0].stunumber);
        $("#phone").val(data[0].phone);
        $("#academy").val(data[0].academy);
        $("#classs").val(data[0].classs);
        $("#rolename").val(data[0].rolename);
        $("#remark").val(data[0].remark);
        $("#address").val(data[0].address);


    })
}

//保存编辑后的信息
function doSubmit() {
    $("#loading").removeClass('hide').addClass('show');
    $.post("../userList/updateByPrimaryKeySelective?_method=PUT", $('#Eidtform').serialize(), function (data) {
        if (data.resultCode == 201) {
            $("#loading").removeClass('show').addClass('hide');
            bootbox.alert(data.resultMessage);
        } else if (data.resultCode == 202) {
            $("#loading").removeClass('show').addClass('hide');
            bootbox.alert(data.resultMessage);
        } else if (data.resultCode == 200) {
            $("#loading").removeClass('show').addClass('hide');
            bootbox.alert(data.resultMessage);
            grid.trigger('reloadGrid');
            $('#editmyModal').modal('hide');
        }
    });
}

//删除记录
function openDelete(str) {
    array = str.split(",");
    bootbox.confirm("您确定要删除该用户吗?", function (result) {
        if (result) {
            if (str == localStorage.getItem("userId")) {
                bootbox.alert("不能删除自己！");
                return;
            }
            $.post("../userList/deleteByPrimaryKey", {
                "id": str,
                "_method": "DELETE",
            }, function (data) {
                if (data.resultCode = 200) {
                    bootbox.alert("删除成功！");
                } else {
                    bootbox.alert("删除失败！");
                }
                grid.trigger('reloadGrid');
            });
        }
    });
}

//清除表单
function clearForm() {
    //清空内容
    $("#id").val("");
    $("#title").val("");
    $("#bz").val("");
    $("#wz").val("");

    //清除验证状态
    $("#addform .form-group").removeClass('has-info').removeClass('has-error');
}

